package y2016.date0606.pm.拼接图片;

import org.junit.jupiter.api.Test;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class MergeImage {

    public static BufferedImage getBufferedImage(String ImageUrl) {
        File file = new File(ImageUrl);
        BufferedImage bi = null;
        try {
            bi = ImageIO.read(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bi;
    }

    public static boolean saveImage(BufferedImage savedImg, String saveDir,
                                    String fileName, String format) {
        boolean flag = false;
        String fileUrl = saveDir + fileName;
        File file = new File(fileUrl);
        try {
            flag = ImageIO.write(savedImg, format, file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return flag;
    }

    public static BufferedImage mergeImage(BufferedImage img1, BufferedImage img2, boolean isHorizontal) {
        int w1 = img1.getWidth();
        int h1 = img1.getHeight();
        int w2 = img2.getWidth();
        int h2 = img2.getHeight();

        // 从图片中读取RGB
        int[] ImageArrayOne = new int[w1 * h1];
        ImageArrayOne = img1.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中
        int[] ImageArrayTwo = new int[w2 * h2];
        ImageArrayTwo = img2.getRGB(0, 0, w2, h2, ImageArrayTwo, 0, w2);

        // 生成新图片
        BufferedImage DestImage = null;
        if (isHorizontal) { // 水平方向合并
            DestImage = new BufferedImage(w1 + w2, h1, BufferedImage.TYPE_INT_RGB);
            DestImage.setRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            DestImage.setRGB(w1, 0, w2, h2, ImageArrayTwo, 0, w2);
        } else { // 垂直方向合并
            DestImage = new BufferedImage(w1, h1 + h2,
                    BufferedImage.TYPE_INT_RGB);
            DestImage.setRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            DestImage.setRGB(0, h1, w2, h2, ImageArrayTwo, 0, w2); // 设置下半部分的RGB
        }

        return DestImage;
    }

    private static String oldDir = "C:/Users/LuTao/Desktop/1/";
    private static String newDir = "C:/Users/LuTao/Desktop/2/";

    private static void doMuch() {
        // 读取待合并的文件
        BufferedImage bi1 = null;
        BufferedImage bi2 = null;
        BufferedImage destImg = null;

        for (int i = 23; i < 509; i = i + 2) {
            int j = i + 1;

            bi1 = getBufferedImage(oldDir + i + ".png");
            bi2 = getBufferedImage(oldDir + j + ".png");
            destImg = mergeImage(bi1, bi2, false);
            saveImage(destImg, newDir, i / 2 + ".png", "png");
            System.out.println("水平合并完毕!" + i / 2);
        }


    }

    @Test
    public void main() throws Exception {

        doMuch();

    }
}


